package cn.edu.tju.elm.controller;

import cn.edu.tju.elm.common.response.HttpResult;
import cn.edu.tju.elm.exception.MethodArgumentNotValidException;
import cn.edu.tju.elm.service.ImageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/images")
@Tag(name = "图片管理", description = "提供图片上传功能，支持JPG和PNG格式，文件大小限制为10MB")
public class ImageController {

    private final ImageService imageService;

    public ImageController(ImageService imageService) {
        this.imageService = imageService;
    }

    /**
     * 上传图片接口
     * @param file 前端上传的图片文件
     * @return 图片的访问 URL
     */
    @PostMapping("")
    @Operation(
            summary = "上传图片",
            description = "上传图片文件到服务器，支持JPG和PNG格式，最大文件大小为10MB"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "上传成功",
                    content = @Content(schema = @Schema(implementation = HttpResult.class))),
            @ApiResponse(responseCode = "400", description = "文件格式不支持或文件过大"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误，上传失败")
    })
    public HttpResult<String> uploadImage(
            @Parameter(
                    description = "图片文件",
                    required = true,
                    content = @Content(mediaType = "multipart/form-data")
            )
            @RequestParam("file") MultipartFile file) {
        // 校验文件类型（仅允许 jpg/png）
        String contentType = file.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
            throw new MethodArgumentNotValidException("仅支持 JPG/PNG 格式");
        }

        // 校验文件大小（限制 10MB）
        long maxSize = 10 * 1024 * 1024;
        if (file.getSize() > maxSize) {
            throw new MethodArgumentNotValidException("文件大小不能超过 10MB");
        }

        // 调用服务层保存图片
        String imageUrl = imageService.saveImage(file);
        return HttpResult.ok(imageUrl);
    }
}